package com.pj.hellomvvm

import android.annotation.SuppressLint
import android.app.Application
import android.content.ContentValues
import android.content.Context
import android.provider.MediaStore
import coil.ImageLoader
import coil.ImageLoaderFactory
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.facebook.flipper.android.AndroidFlipperClient
import com.facebook.flipper.plugins.inspector.DescriptorMapping
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin
import com.facebook.soloader.SoLoader
import com.pj.hellomvvm.manager.QDQQFaceManager
import com.qmuiteam.qmui.QMUILog
import com.qmuiteam.qmui.qqface.QMUIQQFaceCompiler
import com.tencent.mmkv.MMKV
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.*
import xcrash.TombstoneManager
import xcrash.XCrash


@HiltAndroidApp
class SampleApplication:Application(), ImageLoaderFactory {
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        XCrash.init(this)
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
        initQMUILog()
//        QMUISwipeBackActivityManager.init(this)
        QMUIQQFaceCompiler.setDefaultQQFaceManager(QDQQFaceManager.getInstance())
        val rootDir = MMKV.initialize(this)
        LogUtils.e("mmkv root: $rootDir")
        initArouter()
        initDebug()
        initCrash()
    }
    fun initArouter(){
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this); // 尽可能早，推荐在Application中初始化
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun initCrash(){
        GlobalScope.launch(Dispatchers.IO) {
            delay(5000)
            for (file in TombstoneManager.getAllTombstones()) {
                try {
                    val contentValues = ContentValues()
                    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
                    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "txt")
                    val uri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues) ?: continue
                    contentResolver.openOutputStream(uri)?.use { out ->
                        file.inputStream().use { ins ->
                            ins.copyTo(out)
                        }
                    }
                    file.delete()
                }catch (ignore: Throwable){

                }

            }
        }
    }
    private fun initDebug(){
        if(BuildConfig.DEBUG){
            SoLoader.init(this, false)
            val client = AndroidFlipperClient.getInstance(this)
            client.addPlugin(InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()))
            client.start()
        }
    }

    private fun initQMUILog(){
        QMUILog.setDelegete(object : QMUILog.QMUILogDelegate {
            override fun e(tag: String, msg: String, vararg obj: Any) {
                LogUtils.e("$tag : $msg")
            }

            override fun w(tag: String, msg: String, vararg obj: Any) {
                LogUtils.w("$tag : $msg")
            }

            override fun i(tag: String, msg: String, vararg obj: Any) {
                LogUtils.i("$tag : $msg")
            }

            override fun d(tag: String, msg: String, vararg obj: Any) {
                LogUtils.d("$tag : $msg")
            }

            override fun printErrStackTrace(tag: String, tr: Throwable, format: String, vararg obj: Any) {}
        })
    }
    companion object {
        @JvmStatic
        @SuppressLint("StaticFieldLeak")
        var context: Context? = null
            private set
    }

    override fun newImageLoader(): ImageLoader {
        return ImageLoader.Builder(applicationContext)
            .crossfade(true)
            .build()
    }
}
